package mspbots.data.tl.prod.datateams.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.tl.base.AbstractBaseServiceImpl;
import mspbots.data.tl.prod.datateams.mapper.TeamsChannelMapper;
import mspbots.data.tl.prod.datateams.model.ResultMsg;
import mspbots.data.tl.prod.datateams.model.TeamsChannel;
import mspbots.data.tl.prod.datateams.service.TeamsChannelService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * @author Jay.Yang
 */

@Service
@Log4j2
@DS("master")
@RequiredArgsConstructor
public class TeamsChannelServiceImpl extends AbstractBaseServiceImpl<TeamsChannelMapper, TeamsChannel>
        implements TeamsChannelService {

    @Override
    public void sync(ResultMsg resultMsg) {
        JsonNode entity = resultMsg.getEntity();
        TeamsChannel data = TeamsChannel.builder()
                .channelId(resultMsg.getId())
                .email(ObjectUtils.isEmpty(entity.get("email")) ? null : entity.get("email").asText())
                .description(ObjectUtils.isEmpty(entity.get("description")) ? null : entity.get("description").asText())
                .displayName(ObjectUtils.isEmpty(entity.get("displayName")) ? null : entity.get("displayName").asText())
                .groupId(ObjectUtils.isEmpty(entity.get("groupId")) ? null : entity.get("groupId").asText())
                .syncTime(resultMsg.getSyncDate())
                .build();

        data.setTenantCode(resultMsg.getTenantId());

        TeamsChannel dbData = super.baseMapper.selectOne(Wrappers.<TeamsChannel>lambdaQuery()
                .eq(TeamsChannel::getTenantCode, data.getTenantCode())
                .eq(TeamsChannel::getChannelId, data.getChannelId())
                .last("limit 1"));
        if (ObjectUtils.isEmpty(dbData)){
            super.baseMapper.insert(data);
        }else{
            data.setId(dbData.getId());
            super.baseMapper.updateById(data);
        }
    }
}
